package events

import (
	"fmt"

	"github.com/boticord/backend/notifications/app"
	"github.com/boticord/backend/notifications/services"
	"github.com/boticord/backend/notifications/types"
	"github.com/gorilla/websocket"
	"go.uber.org/fx"
)

func newPublishStatsEvent() fx.Option {
	return fx.Module("PublishStats", fx.Invoke(func(tok *services.AuthService, em *app.Emitter, rpc *services.RpcService) {
		app.OnEvent(em, "stats", func(c *websocket.Conn, id string, mt int, data app.Event[types.Stats]) {
			token := tok.GetToken(id)
			if token == "" {
				app.Emit(c, "error", types.Error{
					Code:    types.ErrorCodeUnauthorized,
					Message: "Invalid token",
				})
				return
			}
			info := tok.GetSession(id)
			stats := data.Data
			resp, err := rpc.PublishStats(token, info.Token.ID, stats)
			if err != nil {
				fmt.Printf("err: %s\n", err.Error())
				return
			}
			app.Emit(c, "statsResponse", resp)
		})
	}))
}
